<template>
    <div style="background-color: #ffffff;max-width: auto;height: 100%;">
        <!-- {{ avatarImg }} -->
        <el-form :model="form" ref="userForm" label-width="150px" :rules="rules">
            <!-- {{ form }} -->
            <!-- 用户名称/单位 -->
            <el-form-item label="用户名称/单位" prop="userName">
                <el-input v-model="form.userName" placeholder="请输入用户名称或单位" class="input-width"></el-input>
            </el-form-item>

            <!-- 头像 -->

            <el-form-item label="头像" prop="avatarUrl">

                <el-upload ref="avatarUpload" class="avatar-uploader" action="" :show-file-list="false"
                    accept=".jpg,.png" :auto-upload="false" :on-change="handleChange" :limit="1"
                    :on-exceed="handleExceed">

                    <el-avatar v-if="avatarImg" :src="avatarImg.url" class="avatar"></el-avatar>

                    <el-avatar v-else-if="form.avatarUrl" :src="form.avatarUrl" class="avatar"></el-avatar>

                    <el-avatar v-else class="avatar">
                        <i class="el-icon-user avatar-placeholder"></i>
                    </el-avatar>
                </el-upload>
            </el-form-item>

            <!-- 联系人姓名 -->
            <el-form-item label="联系人姓名" prop="contactName">
                <el-input v-model="form.contactName" placeholder="请输入联系人姓名" class="input-width"></el-input>
            </el-form-item>

            <!-- 联系电话（默认注册手机号码） -->
            <el-form-item label="联系电话" prop="contactPhone">

                <el-input v-model="form.contactPhone" placeholder="请输入联系电话" class="input-width"></el-input>
            </el-form-item>

            <!-- 通信地址（邮寄合同等） -->
            <el-form-item label="通信地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入通信地址" class="input-width"></el-input>
            </el-form-item>

            <!-- 电子邮箱 -->
            <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入电子邮箱" class="input-width"></el-input>
            </el-form-item>

            <!-- 确定修改信息按钮 -->
            <el-form-item label=" ">
                <el-button type="primary" @click="onSubmit">确定修改信息</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { userInfo, checkTokenAndFetchUserInfo } from '@/utils/auth';

const { proxy } = getCurrentInstance(); // 获取当前实例以访问全局属性

const avatarImg = ref(''); // 
const avatarUpload = ref(); //

const form = ref({
    userName: '', // 用户名称/单位
    avatarUrl: '', // 头像URL
    contactName: '', // 联系人姓名
    contactPhone: '', // 联系电话（默认注册手机号码）
    address: '', // 通信地址
    email: '' // 电子邮箱
})


const handleExceed = (files, fileList) => {
    // ElMessage.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    fileList.splice(0, fileList.length, files[0]);

    avatarImg.value.raw = files[0];
    avatarImg.value.url = URL.createObjectURL(files[0]);
}

const handleChange = (file, fileList) => {
    const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
    const isLt2M = file.raw.size / 1024 / 1024 < 5;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 格式!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 5MB!');
        return false;
    }
    console.log('file', file, fileList);
    // 每次选择新的图片时，清空 fileList 并只保留当前选择的文件
    fileList.splice(0, fileList.length, file);
    avatarImg.value = file;
    avatarImg.value.url = URL.createObjectURL(file.raw);
    // 生成文件的 URL 供预览使用
}

const rules = ref({
    userName: [
        { required: true, message: '用户名称/单位必须填写', trigger: 'blur' }
    ],
    contactName: [
        { required: true, message: '联系人姓名必须填写', trigger: 'blur' }
    ],
    contactPhone: [
        { required: true, message: '联系电话必须填写', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '通信地址必须填写', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '电子邮箱必须填写', trigger: 'blur' }
    ],
});


onMounted(async () => {
    await checkTokenAndFetchUserInfo();
    if (!userInfo.value) {
        ElMessage.error('您还未登录，请先登录');
        return false
    }
    Object.keys(userInfo.value).forEach(function (key) {
        console.log(key, userInfo.value[key]);
        if (key in form.value) { // or obj1.hasOwnProperty(key)
            form.value[key] = userInfo.value[key];
        }
    });
})

const uploadAvatar = async () => {
    const ImageData = new FormData();
    ImageData.append('file', avatarImg.value.raw);
    try {
        const res = await proxy.$axios.post('/app/base/comm/upload', ImageData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
        if (res.data.code !== 1000) {
            ElMessage.error('头像上传失败');
            throw new Error(res.data.message);
        }
        form.value.avatarUrl = res.data.data
    } catch (err) {
        ElMessage.error('头像上传失败');
        throw new Error(err);
    }
}

const userForm = ref()
const onSubmit = async () => {
    userForm.value.validate(async (valid) => {
        if (valid) {
            if (!userInfo.value) {
                ElMessage.error('您还未登录，请先登录');
                return false
            }
            await uploadAvatar()
            updateInfo()
        } else {
            ElMessage.error('请检查表单填写');
            return false;
        }
    });

}

const emit = defineEmits(['closeUserInfoView', 'afterSubmit']);
const updateInfo = async () => {
    const res = await proxy.$axios.post('app/user/info/updatePerson', form.value);
    if (res.data.code === 1000) {
        ElMessage.success('修改成功');
        emit('closeUserInfoView');
        emit('afterSubmit');
    } else {
        ElMessage.error('修改失败');
    }
}
</script>

<style scoped>
.input-width {
    width: 90%;
}

.avatar-uploader {
    display: inline-block;
    cursor: pointer;
}

.avatar-placeholder {
    font-size: 48px;
    color: #8c939d;
    display: flex;
    justify-content: center;
    align-items: center;
}

:deep(.el-form-item__label) {
    color: #606266;
    font-size: medium;
}

:deep(.el-form-item__content) {
    margin-left: 20px;
}
</style>
